<?php
error_reporting(E_ERROR);
?>


<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>"
	enctype="multipart/form-data">
<table class="form-table">
	<tbody>
		<tr valign="top">
			<th scope="row"><label for="concurso">Seleccionar archivo csv <a
				href="ejemplo.csv">ejemplo</a></label></th>
			<td><input type="file" class="regular-text" value="" id="csv_file"
				name="csv_file"></td>
		</tr>

		<tr valign="top">
			<th scope="row"><label for="">&nbsp;</label></th>
			<td><input type="submit" class="xregular-text" value="Importar"></td>
		</tr>
	</tbody>
</table>
</form>


<?php
function show($msg,$type='error'){
	echo "<div class='{$type}'>{$msg}</div>";
}

if ('POST' == $_SERVER['REQUEST_METHOD']) {
	if (empty($_FILES['csv_file']['tmp_name'])) {
		show('No hay archivos para procesar');
		return;
	}

	require_once 'File_CSV_DataSource/DataSource.php';

	$time_start = microtime(true);
	$csv = new File_CSV_DataSource;
	$file = $_FILES['csv_file']['tmp_name'];

	if (!$csv->load($file)) {
		show('No es un archivo valido');
		return;
	}

	// pad shorter rows with empty values
	$csv->symmetrize();
	$headers = $csv->getHeaders();

	$data[]=array();
	foreach ($csv->connect() as $csv_data) {
		$data[]=$csv_data;
	}

	$importador = new Importador($headers,$data);

	$table = new Table($data,$headers);
	$table->draw();

	echo "<br>";

	$categories = $importador->getCategories();
	$table = new Table($categories,array('categories'));
	$table->draw();

	echo "<br>";

	$tags = $importador->getTags();
	$table = new Table($tags,array('tags'));
	$table->draw();

	echo "<br>";

	$menus = $importador->getMenus();
	$table = new Table($menus,array('menus'));
	$table->draw();
	
	echo "<br>";
	$table = new Table($importador->categories,array('Category','ID'));
	$table->draw();
	
	echo "<br>";
	$table = new Table($importador->tags,array('Tag','ID'));
	$table->draw();
	
	echo "<br>";
	$table = new Table($importador->menus,array('Menu','ID'));
	$table->draw();	
	
	echo "<br>";
	$table = new Table($importador->posts,array('Post','ID'));
	$table->draw();		
}




/*
 wp_insert_attachment($object);
 wp_insert_category($catarr);
 wp_insert_comment($commentdata);
 wp_insert_link($linkdata);
 wp_insert_post($postarr);
 wp_insert_term($term, $taxonomy, $args);
 wp_insert_user($userdata);
 */



class Importador{
	public $data;
	public $headers;

	public $categories;
	public $tags;
	public $menus;
	public $posts;
	
	private $_categories;
	private $_tags;
	private $_menus;

	public function __construct($headers,$data){
		$this->headers = $headers;
		$this->data = $data;

		$this->_categories=$this->_parse('categories');
		$this->_tags=$this->_parse('tags');
		$this->_menus=$this->_parse('menus');
		
		$this->createCategories();
		$this->createTags();
		$this->createMenus();
		$this->createPosts();
	}

	public function createMenus(){
		$_menus = array();
		foreach($this->_menus as $m){
			$id = wp_create_nav_menu($m);
			$_menus[$m]=array($m,$id);	
		}
		$this->menus=$_menus;    
	}
	
	public function processMenus($data){
		
    $id = $this->posts[$data['title']][1];
		$menus=explode(',', $data['menus']);
    $j=1;
		foreach($menus as $m){
			$menu_id = $this->menus[$m][1];
          	$itemData =  array(
              'menu-item-object-id' =>$id,
              'menu-item-parent-id' => 0,
              'menu-item-position'  => $j++,
              'menu-item-object' => $data['object'],
              'menu-item-type'      => $data['type'],
              'menu-item-status'    => 'publish'
            );
            
            wp_update_nav_menu_item($menu_id, 0, $itemData); 			
		}
		
	}
	
	public function createPost($data){
		

		
	    $new_post = array(
            'post_title'   => $data['title'],
            'post_content' => $data['content'],
            'post_status'  => $data['status'],
            'post_type'    => $data['type'],
//            'post_date'    => $this->parse_date($data['csv_post_date']),
            'post_excerpt' => $data['excerpt'],
//            'post_name'    => $data['csv_post_slug'],
            'post_author'  => $data['author'],
//            'tax_input'    => $this->get_taxonomies($data),
//            'post_parent'  => $data['csv_post_parent'],
        );

        $id = wp_insert_post($new_post);

        $this->posts[$data['title']]=array($data['title'],$id);
	}
	
	
	public function createPosts(){
		foreach($this->data as $d){
			$this->createPost($d);
			$this->processMenus($d);
		}
	}
	
	public function createTags(){
		$taxonomy='post_tag';
		$_tags = array();
		foreach($this->_tags as $t){
			$terms = wp_insert_term($t, $taxonomy);
			$_tags[$t]=array($t,$terms['term_id']);
		}
		$this->tags = $_tags;
	}
	
	public function createCategories(){
		$data['category_parent'] = 0;
		$_cats = array();
		foreach($this->_categories as $c){
			$data['cat_name'] = $c;
			$id = wp_insert_category($data,$error);
			$_cats[$c]=array($c,$id);
		}
		$this->categories = $_cats;
	}

	public function getMenus(){
		return $this->_menus;
	}

	public function getTags(){
		return $this->_tags;
	}

	public function getCategories(){
		return $this->_categories;
	}

	private function _parse($key){
		$k = array_search($key, $this->headers );

		$_d=array();
		foreach($this->data as $d){
			$_d= array_merge($_d,  explode(',', $d[$this->headers[$k]]) );
		}
		$_d=array_unique($_d);
		sort($_d);
		unset($_d[ array_search('',$_d)  ]);
		return $_d;
	}

}






class Table {
	protected $opentable = "\n<table cellspacing='0' cellpadding='0' class='widefat'>\n";
	protected $closetable = "</table>\n";

	protected $openrow = "\t<tr>\n";
	protected $closerow = "\t</tr>\n";

	protected $openHead = "\t<thead>\n";
	protected $closeHead = "\t</thead>\n";

	protected $openBody = "\t<tbody>\n";
	protected $closeBody = "\t</tbody>\n";

	function __construct($data,$header) {
		$this->string = $this->opentable;

		$this->string .= $this->buildHeader($header);
		$this->string .= $this->buildBody($data);

		$this->string .= $this->closetable;
	}

	function buildHeader($row) {
		$html .= $this->openHead;
		$html .= $this->openrow;
		foreach ($row as $field) {
			$html .= $this->addfieldHeader($field);
		}
		$html .= $this->closerow;
		$html .= $this->closeHead;
		return $html;
	}

	function buildBody($data) {
		$html .= $this->openBody;

		if(!is_array(current($data))){
			//es array unidimensional
			foreach ($data as $field) {
				$html .= $this->openrow;
				$html .= $this->addfield($field);
				$html .= $this->closerow;
			}

		}else{
			foreach ($data as $row) {
				$this->string .= $this->buildrow($row);
			}
		}
		$html .= $this->closeBody;
		return $html;
	}

	function buildrow($row) {
		$html .= $this->openrow;
		foreach ($row as $field) {
			$html .= $this->addfield($field);
		}
		$html .= $this->closerow;
		return $html;
	}

	function addfield($field, $style = "null") {
		if ($style == "null") {
			$html =  "\t\t<td>" . strip_tags ($field) . "</td>\n";
		} else {
			$html = "\t\t<td class=\"" . $style . "\">"  . strip_tags ($field) . "</td>\n";
		}
		return $html;
	}

	function addfieldHeader($field, $style = "null") {
		if ($style == "null") {
			$html =  "\t\t<th>" . $field . "</th>\n";
		} else {
			$html = "\t\t<th class=\"" . $style . "\">"  . $field . "</th>\n";
		}
		return $html;
	}

	function draw() {
		echo $this->string;
    }
}

